class Commitment {
    static PENDING = '待定';
    static FULFILLED = '成功';
    static REJCECT = '拒绝'
    constructor(func) {
        this.status = Commitment.PENDING;
        this.result = null
        this.resolveCallback = []
        this.rejectCallback = []
        try {
            func(this.resolve.bind(this), this.reject.bind(this))
        } catch (error) {
            this.reject(error)
        }
    }
    resolve(result) {
        setTimeout(() => {
            if (this.status === Commitment.PENDING) {
                this.status = Commitment.FULFILLED;
                this.result = result
                this.resolveCallback.forEach(callback => {
                    callback(result)
                })
            }
        })
    }
    reject(result) {
        setTimeout(() => {
            if (this.status === Commitment.PENDING) {
                this.status = Commitment.REJCECT;
                this.result = result
                this.rejectCallback.forEach(callback => {
                    callback(result)
                });
            }
        })

    }
    then(onFUFILLED, onREJECT) {
        return new Commitment((resolve, reject) => {
            onFUFILLED = typeof onFUFILLED === 'function' ? onFUFILLED : () => {}
            onREJECT = typeof onREJECT === 'function' ? onREJECT : () => {}
            if (this.status === Commitment.PENDING) {
                this.resolveCallback.push(onFUFILLED)
                this.rejectCallback.push(onREJECT)
            }
            if (this.status == Commitment.resolve) {
                setTimeout(() => {
                    onFUFILLED(this.result)
                })
            }
            if (this.status == Commitment.reject) {
                setTimeout(() => {
                    onREJECT(this.result)
                })
            }
        })
    }
}
console.log('第一步');
let commitment = new Commitment((resolve, reject) => {
    console.log('第二步');
    setTimeout(() => {
        resolve('这次一定 成功')
        reject('下次一定 失败')
        console.log('第四步');
    })

})
commitment.then(
    res => {
        console.log(res);
    },
    res => {
        console.log(res)
    }
).then(
    res => {
        console.log(res);
    },
    res => {
        console.log(res)
    }
)
console.log('第三步');